package com.triones.biz.infra.controller.web.file;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.triones.biz.infra.controller.enums.SceneEnum;
import com.triones.framework.common.util.servlet.ServletUtils;
import com.triones.biz.infra.entity.file.bo.FileBO;
import com.triones.biz.infra.entity.file.vo.FileUploadVO;
import com.triones.biz.infra.entity.file.vo.FileVO;
import com.triones.biz.infra.service.file.FileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
import java.util.List;

/**
 * 管理后台 - 文件存储
 *
 * @author triones
 * 2023-09-20
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/infra/file")
public class FileController extends BaseController {
    private final FileService fileService;
    private final RuoYiConfig ruoYiConfig;

    /**
     * 查询文件列表
     */
    @SaCheckPermission("infra:file:list")
    @GetMapping("/list")
    public TableDataInfo<FileVO> list(@Validated(QueryGroup.class) FileBO bo, PageQuery pageQuery) {
        return fileService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询文件基于id串
     *
     * @param ids 文件ID串
     */
    @SaCheckPermission("infra:file:list")
    @GetMapping("/listByIds/{ids}")
    public R<List<FileVO>> listByIds(@NotEmpty(message = "主键不能为空")
                                     @PathVariable Long[] ids) {
        List<FileVO> list = fileService.listByIds(Arrays.asList(ids));
        return R.ok(list);
    }

    @GetMapping("/{configId}/get/**")
    @SaIgnore
    public void getFileContent(HttpServletRequest request,
                               HttpServletResponse response,
                               @PathVariable("configId") Long configId) throws Exception {
        // 获取请求的路径
        String path = StrUtil.subAfter(request.getRequestURI(), "/get/", false);
        if (StrUtil.isEmpty(path)) {
            throw new IllegalArgumentException("结尾的 path 路径必须传递");
        }
        // 读取内容
        byte[] content = fileService.getFileContent(configId, path);
        if (content == null) {
            log.warn("[getFileContent][configId({}) path({}) 文件不存在]", configId, path);
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return;
        }
        ServletUtils.writeAttachment(response, path, content);
    }

    /**
     * 上传文件
     * 上传文件，没有记录操作日志的必要
     */
//    @SaCheckPermission("infra:file:add")
    @PostMapping("/upload")
    public R<FileVO> uploadFile(FileUploadVO uploadVO, String scene) throws Exception {
        MultipartFile file = uploadVO.getFile();
        String path = uploadVO.getPath();
        FileVO fileVo = fileService.upload(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream()),scene);
        return R.ok(fileVo);
    }

    /**
     * 删除文件
     *
     * @param ids 主键串
     */
    @SaCheckPermission("infra:file:remove")
    @Log(title = "删除文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) throws Exception {
        return toAjax(fileService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


}
